﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using RBAC.Api.Demain.Entities;
using RBAC.Api.Erroc;
using RBAC.Api.Infaction;
using RBAC.Api.Writh.Command.Roles;
using System.Runtime.CompilerServices;
using Yitter.IdGenerator;

namespace RBAC.Api.Writh.CommandHandler.Roles
{
    public class AddRoleCommandHandler : IRequestHandler<AddRoleCommand, APIResult<object>>
    {
        private readonly IBaseRepositry<Role> role;
        private readonly IMapper mapper;
        private readonly IBaseRepositry<RolePermission> rolePermission;
        private readonly ILogger<AddRoleCommandHandler> logger1;

        public AddRoleCommandHandler(IBaseRepositry<Role> baseRepositry, IMapper mapper
                                    ,IBaseRepositry<RolePermission> baseRepositry1,
                                     ILogger<AddRoleCommandHandler> logger1)
        {
            this.role = baseRepositry;
            this.mapper = mapper;
            this.rolePermission = baseRepositry1;
            this.logger1 = logger1;
        }
        public async Task<APIResult<object>> Handle(AddRoleCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result=new APIResult<object>();
            result.Code=ResultCode.Success;
            result.Message="添加角色成功";

            //创建执行
            var strategy=role.Context.Database.CreateExecutionStrategy();
            //使用事务
            await strategy.ExecuteAsync(async () =>
            {
                using(var tran=await role.Context.Database.BeginTransactionAsync())
                {
                    try
                    {
                        var roles=mapper.Map<Role>(request);
                        logger1.LogInformation($"添加角色:{roles}");
                        await role.Add(roles);

                        //添加角色权限
                        foreach(var item in request.PermissionId)
                        {
                            RolePermission permission = new RolePermission
                            {
                                RoleId= roles.Id,
                                PermissionId=item,
                                CreateTime = DateTime.Now,

                            };
                            logger1.LogInformation($"添加角色权限:{permission}"); 
                            await rolePermission.Add(permission);
                        };

                        await tran.CommitAsync();

                    }
                    catch (Exception ex)
                    {
                        logger1.LogError($"添加角色失败:{ex.Message}");
                        await tran.RollbackAsync();
                        
                    }
                }
            });
            return result;
        }
    }
}
